/**
 * 处理拖拽文件和粘贴文件
 * 可搭配 components/FileSendPreview 组件，发送这些文件
 */
import { useRefValue } from '@gnlab/utils/env-react'
import { useStreams } from '@/lib/utils'
import services from '@/services'

function parseFiles(dataTransfer: DataTransfer) {
  return [...dataTransfer.items]
    .filter(item => item.kind === 'file')
    .map(item => item.getAsFile())
    .filter((file): file is File => file !== null)
}

export function useDropFiles(onDropped: (files: File[]) => void) {
  const [contact] = useStreams(services.contacts.current.contact)
  const [dragging, setDragging] = useState(false)
  const draggingRef = useRefValue(dragging)

  const onDragOver = useCallback(
    (e: React.DragEvent) => {
      if (!contact) return
      e.preventDefault()
      if (!draggingRef.current) setDragging(true)
    },
    [contact, draggingRef],
  )

  const onDrop = useCallback(
    (e: React.DragEvent) => {
      if (!contact) return
      e.preventDefault()
      setDragging(false)

      const files = parseFiles(e.dataTransfer)
      if (files.length) onDropped(files)
    },
    [contact, onDropped],
  )

  return {
    props: {
      onDrop,
      onDragOver,
    },
    dragging,
  }
}

export function usePasteFiles(onPasted: (files: File[]) => void) {
  const onPaste = useCallback(
    (e: React.ClipboardEvent<HTMLElement>) => {
      const files = parseFiles(e.clipboardData)
      if (files.length) {
        onPasted(files)
        e.preventDefault() // 避免图片附带的文本信息残留在文本框里
      }
    },
    [onPasted],
  )

  return {
    onPaste,
  }
}
